<?php
/**
 * date: 2018-11-28
 *
 * author: Jason ZHENG <mingjun.zheng@zengduokeji.com>
 *
 * class:WishlistController
 */
namespace App\Http\Controllers;

use App\Common\Base;
use App\Service\DataReturnService as DRS;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class WishlistController extends Controller {

	public function __construct() {
	}

	/**
	 * 2018-11-28
	 *
	 * Jason ZHENG <mingjun.zheng@zengduokeji.com>
	 *
	 * 将商品添加到心愿单（收藏商品）
	 */
	public function add_del(Request $request) {
		$postData = $request->post();
		$validator = Validator::make($postData,
			[
				'token' => 'required|string',
				'product_id' => 'required|string',
			]);
		if ($validator->fails()) {
			return DRS::returnError(1000, '验证错误！', $validator->errors());
		}
		// 用户登陆token验证
		$userInfo = Base::getUserByTokenWithPhone($postData['token']);
		if ($userInfo['code'] != '666') {
			return $userInfo;
		}
		$user = $userInfo['data'];
		$product_info = DB::table('product')->where(['id' => $postData['product_id']])->first();
		if ($product_info == null) {
			return DRS::returnError(10001, '该商品不存在');
		}
		$user_wishlist = DB::table('product_wishlist')->where(['user_id' => $user['id'], 'product_id' => $postData['product_id']])->first();

		// 如果不存在，则收藏
		if ($user_wishlist == null) {
			$inser_data = [
				'user_id' => $user['id'],
				'product_id' => $postData['product_id'],
				'create_time' => date('Y-m-d H:i:s'),
			];
			$add_wishlist = DB::table('product_wishlist')->insert($inser_data);
			if ($add_wishlist) {
				return DRS::returnOk([], '收藏成功');
			} else {
				return DRS::returnError(10001, '收藏失败，请稍后重试');
			}
		} elseif ($user_wishlist->state == 0) {
			//如果已存在，并且是收藏状态，则取消收藏
			$update_data = [
				'state' => 1,
				'cancel_time' => date('Y-m-d H:i:s'),
				'update_time' => date('Y-m-d H:i:s'),
			];
			$update_wishlist = DB::table('product_wishlist')
				->where(['user_id' => $user['id'], 'product_id' => $postData['product_id']])
				->update($update_data);
			if ($update_wishlist) {
				return DRS::returnOk([], '取消收藏成功');
			} else {
				return DRS::returnError(10001, '取消失败，请稍后重试');
			}
		} elseif ($user_wishlist->state == 1) {
			// 如果已存在，但是取消状态，则变成是收藏
			$update_data = [
				'state' => 0,
				'update_time' => date('Y-m-d H:i:s'),
			];
			$update_wishlist = DB::table('product_wishlist')
				->where(['user_id' => $user['id'], 'product_id' => $postData['product_id']])
				->update($update_data);
			if ($update_wishlist) {
				return DRS::returnOk([], '收藏成功');
			} else {
				return DRS::returnError(10001, '收藏失败，请稍后重试');
			}
		}
		return DRS::returnOk([], 'OK');
	}

}